from django.shortcuts import render

# Create your views here.


from rest_framework.generics import ListAPIView,RetrieveAPIView
from .models import Area
from . import serializers
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework.viewsets import ReadOnlyModelViewSet
#方法一
# class AreasView(ListAPIView):
#     '''省份列表'''
#     #指定序列化器
#     serializer_class = serializers.AreasSerializer
#     #获取查询集
#     queryset = Area.objects.filter(parent=None)
#
# class AreaView(RetrieveAPIView):
#     serializer_class = serializers.AreaSerializer
#     queryset = Area.objects.all()


#方法二
#设置缓存类，必须放在最左边
class AreasViewSet(CacheResponseMixin,ReadOnlyModelViewSet):
    #在当前视图类中关闭列表分页功能
    pagination_class = None

    #根据判断选择不同的序列化器类
    def get_serializer_class(self):
        if self.action=='list':
            '''如果url中没有附带PK,则当前的请求为list'''
            return serializers.AreasSerializer
        else:
            return serializers.AreaSerializer

    #根据判断选择不同的查询集,默认返回queryset属性,list和retrieve是属性名
    def get_queryset(self):
        if self.action=='list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()